//
//  MJCollectionViewController.m
//  快速集成下拉刷新
//
//  Created by mj on 14-1-3.
//  Copyright (c) 2014年 itcast. All rights reserved.
//
/*
 具体用法：查看MJRefresh.h
 */
NSString *const MJCollectionViewCellIdentifier = @"Cell";

/**
 *  随机颜色
 */
#define TAG 10000
#define MJRandomColor [UIColor colorWithRed:arc4random_uniform(255)/255.0 green:arc4random_uniform(255)/255.0 blue:arc4random_uniform(255)/255.0 alpha:1]

#import "MJCollectionViewController.h"
#import "Network_Operation.h"
#import "UIImageView+AFNetworking.h"
#import "ScrollPhotoView.h"
@interface MJCollectionViewController ()
/**
 *  存放假数据
 */
@property (strong, nonatomic) NSMutableArray *fakeColors;
@end

@implementation MJCollectionViewController

#pragma mark - 初始化
- (id)init
{
    // UICollectionViewFlowLayout的初始化（与刷新控件无关）
    self.layout = [[UICollectionViewFlowLayout alloc] init];
   // layout.itemSize = CGSizeMake(60, 80);
    self.layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.layout.minimumInteritemSpacing = 0;
    self.layout.minimumLineSpacing = 10;
    //layout.headerReferenceSize = CGSizeMake(0,0);
    //layout.footerReferenceSize = CGSizeMake(100,100);
    self.layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    return [self initWithCollectionViewLayout:self.layout];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   // self.view.backgroundColor = [UIColor redColor];
    // 1.初始化collectionView
    self.num = 4;
    self.pagenum = 0;
    self.pageBtnnum = 1;
    self.view.clipsToBounds = YES;
    [self setupCollectionView];
    
    self.allPage = [self.thumbPage count];
    self.clickView = [[UIView alloc] init];
    self.clickView.frame = Frame(0,0,225,150);
    self.clickView.backgroundColor = [UIColor grayColor];
    self.clickView.alpha = 0.3;
    self.clickNum = 0;
    
    setViewCorner(self.clickView,8);
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self.clickView addGestureRecognizer:panGestureRecognizer];
    self.clickView.tag = TAG;
    
    self.yelloView = [[UIView alloc] init];
    self.yelloView.frame = Frame(2,2,221,146);
    setViewCorner(self.clickView,8);
    self.yelloView.backgroundColor = [UIColor clearColor];
    self.yelloView.layer.borderColor = [UIColor yellowColor].CGColor;
    self.yelloView.layer.borderWidth = 2.0;
    self.flagplay = NO;
    self.figureNum = -1;

}
-(void)counstView:(NSArray *)arr
{
    self.thumbFlag = YES;
    self.thumbPage = [NSMutableArray arrayWithArray:arr];
    NSInteger i = 0;
    if([self.thumbPage count] > 0){
        for(NSDictionary *dic in self.thumbPage){
            if([dic[@"showed"] intValue]){
                self.figureNum = i;
                break;
            }
            i++;
        }
    if(i == [self.thumbPage count]){
            self.figureNum = -1;
        }
        if(self.figureNum == self.clickNum){
            if([self.delegate respondsToSelector:@selector(collectionViewforscreenFlag)]){
                [self.delegate collectionViewforscreenFlag];
            }
        }
    }
    else{
     self.figureNum = -1;
    }
}
- (void)reallocClickView{
    
    self.clickView = [[UIView alloc] init];
    self.clickView.frame = Frame(0,0,225,150);
    self.clickView.backgroundColor = [UIColor grayColor];
    self.clickView.alpha = 0.3;
    self.clickNum = 0;
    setViewCorner(self.clickView,8);
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self.clickView addGestureRecognizer:panGestureRecognizer];
    self.clickView.tag = TAG;
    
}
- (void)reallocPanView{
    
    self.yelloView = [[UIView alloc] init];
    self.yelloView.frame = Frame(2,2,221,146);
    setViewCorner(self.clickView,8);
    self.yelloView.backgroundColor = [UIColor clearColor];
    self.yelloView.layer.borderColor = [UIColor yellowColor].CGColor;
    self.yelloView.layer.borderWidth = 2.0;
    
}
-(void)counstFigureNum:(NSInteger)num
{
    self.figureNum = num;
    if(self.flagplay)
    self.clickNum = num;
}

/*
 *  初始化collectionView
 */
- (void)setupCollectionView
{
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:MJCollectionViewCellIdentifier];
    [self.collectionView setContentSize:CGSizeMake(0,0)];
}

/**
 为了保证内部不泄露，在dealloc中释放占用的内存
 */
-(void)viewDidUnload
{
    [super viewDidUnload];
   self.layout = nil;
   self.clickView = nil; //点击后的view
    
    self.yelloView = nil;
    self.panView = nil;
}
-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    self.layout = nil;
    self.clickView = nil; //点击后的view
    
    self.yelloView = nil;
    self.panView = nil;
}
- (void)dealloc
{
    NSLog(@"MJCollectionViewController--dealloc---");
}

#pragma mark - collection数据源代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSInteger dataNum = [self.thumbPage count];
    if(!dataNum){
        self.nowThumb = dataNum;
        return dataNum;
    }
    if(self.num == CLOSEPAGE){
        if(dataNum <= self.pageBtnnum*CLOSEPAGE){
            if(self.pageBtnnum == 1){
                self.nowThumb = dataNum;
                return dataNum;
            }
            else{
                self.nowThumb = (dataNum - (self.pageBtnnum-1)*CLOSEPAGE);
                return (dataNum - (self.pageBtnnum-1)*CLOSEPAGE);
                
                }
        }
        else{
            self.nowThumb = self.num;
            return self.num;
        }
    
    }
    else if(self.num == OPENPAGE){
        
        if(dataNum <= self.pageBtnnum*OPENPAGE){
            if(self.pageBtnnum == 1){
                self.nowThumb = dataNum;
                return dataNum;
            }
            else{
                self.nowThumb = (dataNum - (self.pageBtnnum-1)*OPENPAGE);
                return (dataNum - (self.pageBtnnum-1)*OPENPAGE);
            }
        }
        else{
            self.nowThumb = self.num;
            return self.num;
        }
    }
    self.nowThumb = 0;
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
   UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:MJCollectionViewCellIdentifier forIndexPath:indexPath];
    if(!cell){
        cell = [[UICollectionViewCell alloc] init];
    }
    HeadItem *v = (HeadItem *)[cell viewWithTag:(indexPath.row+self.pagenum+2014)];
    if(v){
    [v removeFromSuperview];
    v = nil;
    }
    HeadItem *item = nil;
    
    cell.backgroundColor = [UIColor clearColor];
    
    cell.tag = indexPath.row;
    
    if(self.num == CLOSEPAGE){
    item = LoadFromNib(@"HeadItem");
    }
    else{
    item = LoadFromNib(@"HeadOpenView");
    }
    item.tag = 2014+indexPath.row+self.pagenum;
    item.dataDic = [NSMutableDictionary dictionaryWithDictionary:self.thumbPage[indexPath.row+self.pagenum]];
    [item reloadHeadItem:StringFromId(self.thumbPage[indexPath.row+self.pagenum][@"templateId"]) Name:[NSString stringWithFormat:@"%@%@",@"  ",StringFromId(self.thumbPage[indexPath.row+self.pagenum][@"name"])] Number:[NSString stringWithFormat:@"%ld",indexPath.row+1+self.pagenum]];
    [cell addSubview:item];
    //播放
    if(self.flagplay){
        self.figureNum = self.clickNum;
        if(indexPath.row+self.pagenum == self.figureNum){
            [self.yelloView removeFromSuperview];
            if(!self.yelloView)
            [self reallocPanView];
            [item addSubview:self.yelloView];
        }
    }    
    else{
    if(indexPath.row+self.pagenum == self.clickNum){
    [self.clickView removeFromSuperview];
    if(!self.clickView)
    [self reallocClickView];
    [item addSubview:self.clickView];
    }
    if(indexPath.row+self.pagenum == self.figureNum){
            [self.yelloView removeFromSuperview];
            if(!self.yelloView)
            [self reallocPanView];
            [item addSubview:self.yelloView];
        }
        if(self.clickNum == self.figureNum){
        if([self.delegate respondsToSelector:@selector(collectionViewforscreenFlag)]){
            [self.delegate collectionViewforscreenFlag];
        }
        }
    }
    //加pen手势
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [item addGestureRecognizer:panGestureRecognizer];
    
    NSMutableDictionary *dicthumb = [NSMutableDictionary dictionaryWithDictionary:self.thumbPage[indexPath.row+self.pagenum]];
     if(![@"0" isEqualToString:dicthumb[@"width"]] && ![@"0" isEqualToString:dicthumb[@"height"]]){
        //self.flagplay = YES;
     }
     else{
         self.thumbFlag = NO;
     }
    if(self.thumbFlag && (indexPath.row+1 == self.nowThumb)){
        [[TimerDownImage sharedInstance] stopTimerflushThumb];
    }
    else{
        
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    self.clickNum = indexPath.row+self.pagenum;
    //停止播放
    self.flagplay = NO;
    
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    
    NSLog(@"%ld",(long)cell.tag);
    
    HeadItem *item = (HeadItem *)[cell viewWithTag:(indexPath.row+2014+self.pagenum)];
    
    [self.collectionView reloadData];
    
    if([self.delegate respondsToSelector:@selector(didselectCell:Num:)]){
        [self.delegate didselectCell:item Num:self.clickNum];
    }
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(225, 150);
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(20,0,0,0);
}
-(void)pan:(UIPanGestureRecognizer *)recognizer
{

    HeadItem *item;
    UIView *view = recognizer.view;
    if(view.tag == TAG){
        item = (HeadItem *)view.superview;
    }
    else{
        item = (HeadItem *)recognizer.view;
    }
    UIView *v = self.view.superview;
    ScrollPhotoView *scroView = (ScrollPhotoView *)v.superview;
    NSInteger tag = item.tag;
    HeadItem *scroItem = nil;
    if(self.num == CLOSEPAGE){
    scroView.tuocloseView.frame = Frame((tag-2014-self.pagenum)*234+40,405,225,150);
    scroView.tuocloseView.headImgV.image = item.headImgV.image;
    scroView.tuocloseView.nameLab.text = item.nameLab.text;
    scroView.tuocloseView.hidden = NO;
    [scroView addSubview:scroView.tuocloseView];
    scroItem = scroView.tuocloseView;
    }
    else{
        if((tag-2014-self.pagenum) > 3){
            tag = tag-4;
             scroView.tuoopenView.frame = Frame((tag-2014-self.pagenum)*233+36,395,225,150);
        }
        else{
             scroView.tuoopenView.frame = Frame((tag-2014-self.pagenum)*233+36,235,225,150);
        }
       // scroView.tuoopenView.frame = Frame((tag-2014-self.pagenum)*234+40,405,225,150);
        scroView.tuoopenView.headImgV.image = item.headImgV.image;
        scroView.tuoopenView.nameLab.text = item.nameLab.text;
        scroView.tuoopenView.numberlab.text = item.numberlab.text;
        scroView.tuoopenView.hidden = NO;
        [scroView addSubview:scroView.tuoopenView];
        scroItem = scroView.tuoopenView;
    }
   // self.clickNum = item.tag-2014;
        if (recognizer.state == UIGestureRecognizerStateBegan) {
           
            if(item.tag == TAG){
                
            }
            else{
                
            }
          //  NSLog(@"%ld",(long)item.tag);
            self.initTouchPosY = [recognizer locationInView:item].y;
            self.initTouchPosX = [recognizer locationInView:item].x;
    }
    else if (recognizer.state == UIGestureRecognizerStateChanged) { //status change
         CGFloat panAmount = self.initTouchPosY - [recognizer locationInView:item].y;
         CGFloat panAmountX = self.initTouchPosX - [recognizer locationInView:item].x;
        if (panAmount < 0) {
            //下移
            CGRect r = scroItem.frame;
            r.origin.y -= panAmount;
            r.origin.x -= panAmountX;
            scroItem.frame = r;
            self.tmpr = scroItem.frame;
        }
        else {
            //上移
            CGRect r = scroItem.frame;
            r.origin.y -= panAmount;
            r.origin.x -= panAmountX;
            scroItem.frame = r;
              NSLog(@"%f",scroItem.frame.origin.y);
            self.tmpr = r;
          }
    }
    else if (recognizer.state == UIGestureRecognizerStateEnded ||
             recognizer.state == UIGestureRecognizerStateCancelled){
        NSLog(@"%f",scroView.tuocloseView.frame.origin.y);
        if([self.delegate respondsToSelector:@selector(panCollectionItem:CGRECT:)]){
            [self.delegate panCollectionItem:item.tag-2014 CGRECT:self.tmpr];
        }
    }

}
@end
